<template>
    <el-main>

        <el-row>
            <el-col :span="8">
                <el-form :model="loginForm" status-icon :rules="rules" ref="loginForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="登录用户" prop="username">
                        <el-input type="text" v-model="loginForm.username" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="登录密码" prop="password">
                        <el-input type="password" v-model="loginForm.password" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="login('loginForm')">登录</el-button>
                    </el-form-item>
                </el-form>
            </el-col>
        </el-row>

    </el-main>
</template>

<script>
    export default {
        name: "Login",
        data() {
            return {
                loginForm:{
                    username:'admin',
                    password:'admin'
                },
                rules:{
                    username:[
                        { required: true, message: '请输入登录名称', trigger: 'blur' },
                        { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
                    ],
                    password:[
                        { required: true, message: '请输入登录密码', trigger: 'blur' },
                        { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
                    ]
                }
            }
        },
        methods:{
            login: function (loginForm) {
                let form = this.loginForm;
                if (form.username == null) {
                    this.$message("崩为空");
                    return;
                }
                this.$refs[loginForm].validate((valid) => {
                    if (valid) {
                        this.$message({type: "success", message: "验证通过"})
                        //调用登录接口，如果成功跳转到后台首页
                        this.axios.post("http://localhost:8888/user/login", this.loginForm).then(res => {
                            if (res.data.result) {
                                //存储token到localStorage
                                localStorage.setItem("token", res.data.data)
                                this.$router.push("/index");
                            } else {
                                this.$message(res.data.message);
                            }
                        })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            }
        },
        created() {

        }
    }
</script>

<style scoped>
    .el-row {
        margin-left: 30%;
        margin-top: 10%;
    }

</style>